#pragma once
#include <unistd.h>
#include <signal.h>
#include <functional>
#include "Log.hpp"
#include "Socket.hpp"
extern Log log;

using func_t = std::function<std::string(std::string &)>;
class TcpServer
{
public:
    TcpServer(uint16_t port, func_t callback) : _port(port), _callback(callback)
    {
    }
    ~TcpServer()
    {
    }

public:
    void InitServer()
    {
        _listensocket.Socket();
        _listensocket.Bind(_port);
        _listensocket.Listen();
        log(Info, "tcpserver create done......\n");
    }
    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        std::string clientip;
        uint16_t clientport;
        while (true)
        {
            int sockfd = _listensocket.Accept(&clientip, &clientport);
            if (sockfd == -1)
                continue;
            log(Info, "get a new link, sockfd:%d, clientip:%s, clientport:%d\n", sockfd, clientip.c_str(), clientport);

            // 提供服务
            if (fork() == 0)
            {
                _listensocket.Close();
                // 处理数据
                char inbuffer[1024];
                std::string inbuffer_string;
                while (true)
                {
                    ssize_t n = read(sockfd, inbuffer, sizeof(inbuffer));
                    if (n > 0)
                    {
                        inbuffer[n] = 0;
                        inbuffer_string += inbuffer;
                        log(Debug, "%s\n", inbuffer);
                        // 如果一次性发送多个完整的数据，也能处理

                        while (true)
                        {
                            std::string info = _callback(inbuffer_string);
                            if (info.empty())  break;
                            // write
                            write(sockfd, info.c_str(), info.size());
                        }
                        sleep(1);
                    }
                    else if (n == 0)
                        break;
                    else
                        break;
                }
                exit(0);
            }
            close(sockfd);
        }
    }

private:
    uint16_t _port;
    Sock _listensocket;
    func_t _callback;
};